package com.softlab.retailwholesalesystem.controller;

import com.softlab.retailwholesalesystem.service.exception.*;
import com.softlab.retailwholesalesystem.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

public class BaseController {

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> exceptionHandler(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof ClientNameDuplicatedException){
            result.setStatus(4000);
            result.setMessage("当前客户已存在");
        }
        else if (e instanceof UsernameDuplicatedException){
            result.setStatus(4400);
            result.setMessage("当前用户已存在");
        }
        else if (e instanceof InsertRunTimeException){
            result.setStatus(5000);
            result.setMessage("注册时出现未知错误");
        }
        else if (e instanceof NoUserException){
            result.setStatus(6000);
            result.setMessage("用户名不存在");
        }
        else if (e instanceof PasswordWrongException){
            result.setStatus(7000);
            result.setMessage("密码错误");
        }
        else if (e instanceof DeleteErrorException){
            result.setStatus(8000);
            result.setMessage("删除时遇到错误");
        }
        else if (e instanceof UpdateErrorException){
            result.setStatus(9000);
            result.setMessage("更新时遇到未知错误");
        }
        else if (e instanceof NoSuchStoreException){
            result.setStatus(8888);
            result.setMessage("无库存");
        }

        return result;
    }

    public Integer getIdFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("id").toString());
    }

    public String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }

}
